import React, { useEffect, useState, useCallback } from 'react'
import { connect } from 'react-redux'
import { getHotwords, getSuggests } from 'api/base'
import { Helmet } from 'react-helmet'
import { getSearchHistory, setSearchHistory, clearSearchHistory } from 'utils/playLocal'
import Result from './Result'
import './index.scss'
function Search(props) {
    const {} = props
    const [words, setWords] = useState([])
    const [key, setKey] = useState('')
    const [query, setQuery] = useState('')
    const [suggestList, setSuggestList] = useState('')
    const [history, setHistory] = useState(() => {
        return getSearchHistory() || []
    })
    useEffect(() => {
        getHotwords().then((res) => {
            setWords(res.data.map((e) => e.keyword).slice(0, 8))
        })
    }, [])
    const searchContent = useCallback((e) => {
        if (e.keyCode === 13) {
            const content = e.currentTarget.value
            if (content) {
                setSuggestList([])
                setKey(content)
            }
            setSearchHistory({
                value: content,
                timestamp: new Date().getTime()
            })
        }
    })
    const clearSearch = useCallback(() => {
        setSuggestList([])
        setQuery('')
        setKey('')
        setHistory(getSearchHistory())
    })
    const getSuggest = useCallback((e) => {
        if (e.keyCode !== 13) {
            const content = e.currentTarget.value
            if (content) {
                getSuggests({ w: content }).then((res) => {
                    let suggestList = []
                    if (res.data.tag) {
                        suggestList = res.data.tag.map((item) => ({
                            name: item.name,
                            value: item.value
                        }))
                    }
                    setSuggestList(suggestList)
                    setKey('')
                })
            } else {
                setSuggestList([])
                setKey('')
            }
        }
    })
    const clearHis = useCallback(() => {
        clearSearchHistory()
        setHistory([])
    })
    return (
        <div className="search">
            <Helmet>
                <title>搜索</title>
            </Helmet>
            {/* 搜索框 */}
            <div className="search-top flex middle">
                <div className="search-box flex middle cell-main">
                    <i className="icon-search icon mr5" />
                    <input
                        type="text"
                        autoComplete="off"
                        maxLength={33}
                        placeholder="搜索视频、UP主或AV号"
                        value={query}
                        className="search-input"
                        onChange={(e) => {
                            setQuery(e.currentTarget.value)
                        }}
                        onKeyDown={searchContent}
                        onKeyUp={getSuggest}
                    />
                    {query ? (
                        <img
                            alt="close"
                            src={require('../../assets/images/search-close.png')}
                            className="search-close"
                            onClick={() => {
                                clearSearch()
                            }}
                        />
                    ) : null}
                </div>
                <div
                    className="cancel ml10"
                    onClick={() => {
                        window.history.back()
                    }}
                >
                    取消
                </div>
            </div>
            {!key ? (
                <>
                    <div className="words">
                        <div className="xl item mb5">大家都在搜</div>
                        <div className="flex wrap ">
                            {words.map((e, i) => (
                                <div key={i} className="word-item m">
                                    {e}
                                </div>
                            ))}
                        </div>
                    </div>
                    {// 推荐
                    suggestList.length > 0 ? (
                        <div className="suggest">
                            {suggestList.map((e, i) => (
                                <div className="suggest-item" key={'suggest' + i}>
                                    <p
                                        dangerouslySetInnerHTML={{ __html: e.name }}
                                        onClick={() => {
                                            setKey(e.value)
                                        }}
                                    />
                                </div>
                            ))}
                        </div>
                    ) : null}
                    {
                        // 历史搜索
                        <div className="history">
                            <div className="xl item mb10">历史搜索</div>
                            <div className="history-list">
                                {history.map((e, i) => (
                                    <div className="history-item flex middle">
                                        <img
                                            src={require('../../assets/images/history.png')}
                                            alt=""
                                            className="his-ico"
                                        />
                                        <div className="name ml10">{e.value}</div>
                                    </div>
                                ))}
                            </div>
                            {history.length > 0 ? (
                                <div
                                    onClick={() => {
                                        clearHis()
                                    }}
                                    className="his-clear"
                                >
                                    清除历史记录
                                </div>
                            ) : null}
                        </div>
                    }
                </>
            ) : (
                <div className="result">
                    <Result keyword={key} />
                </div>
            )}
        </div>
    )
}

export default connect(
    function mapStateToProps(state) {
        return state
    },
    function mapDispatchToProps(dispatch) {
        return { dispatch }
    }
)(Search)
